package com.zxf.appliction.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zxf.appliction.dao.ArticleMapper;
import com.zxf.appliction.domain.Article;
import com.zxf.appliction.domain.Content;
import com.zxf.appliction.domain.Params;
import com.zxf.appliction.service.ArticleService;
import com.zxf.appliction.util.DateJsonValueProcessor;
import com.zxf.appliction.util.ExcelHelper;
import com.zxf.appliction.util.ObjectExcelView;

/**
 * 文章信息 ArticleController
 * 
 * @author 郑肖峰
 * @since 2017-5-23 下午2:16:23
 */
@Controller
@RequestMapping("/articles")
public class ArticleController {

	@Autowired
	private ArticleService articleService;

	@Autowired
	ArticleMapper articleMapper;

	private static Logger logger = Logger.getLogger(ArticleController.class); 
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	private static  JSONArray js = new JSONArray();
	/**
	 * 添加文章信息
	 * @param article 
	 * @param publishdate2
	 * @param content
	 * @param request
	 * @param response
	 * @throws ParseException 
	 */
	
	@ResponseBody
	@RequestMapping(value = "/savearticle.do", method = RequestMethod.POST)
	public void saveArticle(Article article, String publishdate2,
			Content content, HttpServletRequest request,
			HttpServletResponse response) throws ParseException  {
		logger.info("savearticle:"+article);
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		
			if (null != publishdate2 && !publishdate2.equals("")) {
				article.setPublishdate(sdf.parse(publishdate2));
			}
		
			int code = articleService.savearticle(article,content);
			if (code < 1) {
				response.setContentType("text/html;charset=UTF-8");
				responseMap.put("method", "savearticle");
				responseMap.put("success", "false");
				responseMap.put("info", "添加失败！");
				return;
			}
			if (code > 0) {
				responseMap.put("method", "savearticle");
				responseMap.put("success", "false");
				responseMap.put("info", "更新成功！");
				response.setContentType("text/html;charset=UTF-8");
			}
		
		
	}
	/**
	 * 文章列表
	 * @param params
	 * @param author
	 * @param title
	 * @param source
	 * @param articleID
	 * @param typeid
	 * @param startime
	 * @param endtime
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */

	// 文章列表
	@RequestMapping(value = "/articlelist.do", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject userList(Params params, String author, String title,
			String source, String articleID, String typeid, String startime,
			String endtime, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();

		try {
			if (null != startime && !"".equals(startime)) {
				params.setStartdate(sdf.parse(startime));
			}
			if (null != endtime && !"".equals(endtime)) {
				params.setEnddate(sdf.parse(endtime));
			}
		} catch (ParseException e) {
			logger.info("articlelist:  日期类型报错",e);
			
		}


		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		
		List articlelist = articleService.getArticleList(params, article);
		int totle = articleService.getartcletotle(params, article);
		
		obj.put("data", js.fromObject(articlelist, jsonConfig));
		obj.put("total", totle); 
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	@RequestMapping("/sele")
	public @ResponseBody
	int list() {
		logger.info(articleMapper.select());
		return articleMapper.select();
	}

	
	/**
	 * 删除文章信息
	 * @param articleID
	 * @param title
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/delarticle.do", method = RequestMethod.POST)
	public void delArticle(String articleID, String title,
			HttpServletRequest request, HttpServletResponse response) {
		int flagadd = 0;
		int delno = 0;
		Map<String, Object> responseMap = new HashMap<String, Object>();
		String[] temarticleID = articleID.split(",");
		String[] temtitle = title.split(",");
		for (int i = 0; i < temarticleID.length; i++) {
			flagadd = articleService.delarticle(Integer
					.parseInt(temarticleID[i]));
			if (flagadd > 0) {
				flagadd = articleService.delcontent(temtitle[i]);
				if (flagadd > 0) {
					delno = delno + 1;
				}
			}
		}
		if (delno == temarticleID.length) {
			responseMap.put("method", "del");
			responseMap.put("success", "true");
			responseMap.put("info", "删除成功！");

			response.setContentType("text/html;charset=UTF-8");
			try {
				response.getWriter().write("{success:true}");
			} catch (IOException e) {
				logger.info("", e);
			}
		}
	}

	
	/**
	 * 查看文章信息
	 * @param articleID
	 * @param title
	 * @param jsonData
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailarticle.do", method = RequestMethod.POST)
	public JSONObject detailArticle(int articleID, 
			String jsonData, HttpServletRequest request,
			HttpServletResponse response) {
		
		Article article;
		Content content;
		JSONObject obj = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		
		if(articleID <= 0){
			obj.put("success", false);
			obj.put("message", "参数为空！");
			return obj;
			
		}
		
		article = articleService.detailarticle(articleID);
		content = articleService.detailcontent(articleID);
		
		Date publishdate2 = article.getPublishdate();
		String publishdate3 = sdf.format(publishdate2);
		
		obj.put("data", JSONArray.fromObject(article, jsonConfig));
		obj.put("content", content);
		obj.put("publishdate2", publishdate3);
		obj.put("success", true);

		logger.info("article:"+obj.toString());

		return obj;
	}

	/**
	 * 导出到Excel
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/excelarticle.do")
	public void doExportTrafficAccount(HttpServletRequest request,
			HttpServletResponse response) {
		// 第一步，创建一个webbook，对应一个Excel文件

		// 构造一个查询条件

		// 创建一个新的Excel
		HSSFWorkbook workBook = new HSSFWorkbook();
		// 创建sheet页
		HSSFSheet sheet = workBook.createSheet();
		// sheet页名称
		workBook.setSheetName(0, "targetStockList");
		// 创建header页
		HSSFHeader header = sheet.getHeader();
		// 设置标题居中
		header.setCenter("标题");
		ObjectExcelView objectExcelView = new ObjectExcelView();

		// 页码

		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List articlelist = articleService.getArticleList();

		// 通过Response把数据以Excel格式保存

		OutputStream out = null;// 创建一个输出流对象

		try {

			response.setContentType("application/msexcel;charset=UTF-8");// 设置类型
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ new String(("用户意见信息表" + ".xls").getBytes("GBK"),
							"ISO8859_1") + "\"");

			// filename是下载的xls的名

			response.setHeader("Pragma", "No-cache");// 设置头

			response.setHeader("Cache-Control", "no-cache");// 设置头

			response.setDateHeader("Expires", 0);// 设置日期头
			out = response.getOutputStream();//
			objectExcelView.exportExcel(articlelist).write(out);

			out.flush();
			out.close();

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			if (out != null) {

				logger.info("out 没有 close");

				try {
					out.close();
				} catch (IOException e) {
					logger.info(e);
				}

			}

		}

		
		
	}

	
	/**
	 * 导入到Excel
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/importExcel.do")
	public JSONObject importExcel(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 页面控件的文件流

		MultipartFile multipartFile = multipartRequest.getFile("excelfile");
		if (null == multipartFile || multipartFile.isEmpty()) {
			multipartFile = multipartRequest.getFile("excelfile");
		}
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		String logoPathDir = "E:/upload/excels";
		// 得到图片保存目录的真实路径
		String logoRealPathDir = logoPathDir;
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoRealPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		// StoreLocation
		String fileName = logoRealPathDir + File.separator + filename;
		File file = new File(fileName);
		// 保存上传文件
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		FileInputStream fis = null;
		List<List> dataList = new ArrayList();
		try {
			fis = new FileInputStream(fileName);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		try {
			dataList = ExcelHelper.getInstanse().excelFileConvertToList(fis);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		for (int i = 1; i < dataList.size(); i++) {
			if (!dataList.get(i).isEmpty() && dataList.get(i).size() > 1) {

				Article article = new Article();
				if (null != dataList.get(i).get(1)) {
					article.setAuthor(dataList.get(i).get(1).toString());

				}
				if (null != dataList.get(i).get(2)) {

					switch (dataList.get(i).get(2).toString()) {
					case "军事":
						article.setChannelid(1);
						break;
					case "财经":
						article.setChannelid(2);
						break;
					case "社会":
						article.setChannelid(3);
						break;
					case "历史":
						article.setChannelid(4);
						break;
					case "文化":
						article.setChannelid(5);
						break;
					default:
						break;

					}
				}
				if (null != dataList.get(i).get(3)) {
					article.setAddeddate(dataList.get(i).get(3).toString());

				}
				if (null != dataList.get(i).get(4)) {
					article.setSource(dataList.get(i).get(4).toString());

				}
				if (null != dataList.get(i).get(5)) {
					article.setTitle(dataList.get(i).get(5).toString());

				}
				if (null != dataList.get(i).get(6)) {
					try {
						article.setPublishdate(sdf.parse(dataList.get(i).get(6).toString()));
					} catch (ParseException e) {
						e.printStackTrace();
					}

				}
				if (null != dataList.get(i).get(7)) {
					article.setSummary(dataList.get(i).get(7).toString());

				}

				if (null != article) {
					int a = articleService.savearticle(article);
					if (a == 1) {
						obj.put("success", true);
					} else {
						obj.put("failure", true);
					}

				}

				logger.info(dataList.get(i));

			}
		}
		deleteDir(file);
		obj.put("success", true);
		return obj;
	}

	/**
	 * 删除空目录
	 * 
	 * @param dir
	 *            将要删除的目录路径
	 */
	private static void doDeleteEmptyDir(String dir) {
		boolean success = (new File(dir)).delete();
		if (success) {
			logger.info("Successfully deleted empty directory: " + dir);
		} else {
			logger.info("Failed to delete empty directory: " + dir);
		}
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

}
